﻿//
// MockObjectSet.cs
//
// Authors:
//    Claus Jørgensen <10229@iha.dk>
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;

namespace RSD.Test
{
    internal static class ObjectSetExtension
    {
        public static IObjectSet<T> AsObjectSet<T>(this IEnumerable<T> entities) where T : class
        {
            return new MockObjectSet<T>(entities);
        }
    }

    internal sealed class MockObjectSet<T> : IObjectSet<T> where T : class
    {
        private readonly ICollection<T> items;
        private readonly IQueryable<T> query;

        public MockObjectSet()
            : this(new HashSet<T>())
        {
        }

        public MockObjectSet(IEnumerable<T> entities)
        {
            items = new HashSet<T>(entities);
            query = items.AsQueryable();
        }

        #region IObjectSet<T> Members

        public void AddObject(T entity)
        {
            items.Add(entity);
        }

        public void Attach(T entity)
        {
            items.Add(entity);
        }

        public void DeleteObject(T entity)
        {
            items.Remove(entity);
        }

        public void Detach(T entity)
        {
            items.Remove(entity);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return items.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return items.GetEnumerator();
        }

        #endregion

        #region IQueryable Members

        public Type ElementType
        {
            get
            {
                return query.ElementType;
            }
        }

        public Expression Expression
        {
            get
            {
                return query.Expression;
            }
        }

        public IQueryProvider Provider
        {
            get
            {
                return query.Provider;
            }
        }

        #endregion
    }
}
